package com.wswy.wzcx.ui.fragment;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.che.libcommon.api.ApiOptionalResultObserver;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.ui.BaseFragment;
import com.che.libcommon.utils.ToastUtils;
import com.che.libcommon.utils.optional.Optional;
//import com.sgoo.ppi.S;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.wswy.wzcx.BuildConfig;
import com.wswy.wzcx.R;
import com.wswy.wzcx.api.Api;
import com.wswy.wzcx.api.ConfigsKt;
import com.wswy.wzcx.jpush.PushChannel;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.UpgradeModel;
import com.wswy.wzcx.model.UserMode;
import com.wswy.wzcx.model.VersionModel;
import com.wswy.wzcx.model.conf.SysConf;
import com.wswy.wzcx.model.home.RPaths;
import com.wswy.wzcx.model.home.RouterUtils;
import com.wswy.wzcx.module.ChannelManager;
import com.wswy.wzcx.module.GlobalConfigManager;
import com.wswy.wzcx.module.MessageCenter;
import com.wswy.wzcx.module.MessageCenter.UpgradeInfoMsg;
import com.wswy.wzcx.module.upgrade.UpgradeConfigure;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.activity.MineActivity;
import com.wswy.wzcx.ui.activity.PwdActivity;
import com.wswy.wzcx.ui.main.MainActUtils;
import com.wswy.wzcx.ui.main.MainActivity;
import com.wswy.wzcx.ui.main.common.UpgradeDialog;
import com.wswy.wzcx.ui.other.AndroidUtilities;
import com.wswy.wzcx.ui.other.LayoutHelper;
import com.wswy.wzcx.ui.other.UpdateTools;
import com.wswy.wzcx.ui.persenter.SettingPresenter;
import com.wswy.wzcx.ui.view.SettingView;
import com.wswy.wzcx.utils.SharedPrefStorage;

import java.util.concurrent.TimeUnit;

import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import kotlin.Unit;
import kotlin.jvm.functions.Function2;

/**
 * Created by wangduheng26 on 2018/1/19.
 * wangduheng26@gmail.com
 */

public class SettingFragment extends BaseFragment implements View.OnClickListener, SettingView {
    public static final String TAG = "SettingFragment";
    private SettingPresenter presenter;
    private View rlPwd;
    private SwitchCompat aSwitchPush;
    private View rlListener, rlPrivacy, rlFeedback;
    private TextView tvLogout;
    private View llVersion;
    private TextView tvVersionStatus;
    private ImageView versionImageView;
    boolean versionChecking = false;
    private boolean hasClick = false;

    private Observer<UpgradeModel> upgradeModelObserver;

    public static SettingFragment newInstance() {
        Bundle args = new Bundle();
        SettingFragment fragment = new SettingFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        presenter = new SettingPresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_setting, container, false);
    }

    DataCenter center;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        rlPwd = view.findViewById(R.id.rl_pwd);
        aSwitchPush = view.findViewById(R.id.switch_push);
        rlListener = view.findViewById(R.id.rl_listener);
        rlPrivacy = view.findViewById(R.id.rl_privacy_policy);
        rlFeedback = view.findViewById(R.id.rl_feedback);
        SysConf conf = GlobalConfigManager.getInstance().getSysConf().getSyLogout();
        if (conf.getValue().equals("1")) {
            rlFeedback.setVisibility(View.VISIBLE);
        } else {
            rlFeedback.setVisibility(View.GONE);
        }
        tvLogout = view.findViewById(R.id.tv_logout);
        llVersion = view.findViewById(R.id.rl_version);
        tvVersionStatus = view.findViewById(R.id.tv_version_state);
        versionImageView = view.findViewById(R.id.imageview);

        center = DataCenter.get();
        LayoutHelper.setSelectable(tvLogout);
        if (!center.hasLogin()) {
            tvLogout.setVisibility(View.GONE);
            rlPwd.setVisibility(View.GONE);
        } else {
            tvLogout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    presenter.showLogoutDialog();
                }
            });
        }
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        rlPwd.setOnClickListener(this);
        rlListener.setOnClickListener(this);
        rlPrivacy.setOnClickListener(this);
        rlFeedback.setOnClickListener(this);
        llVersion.setOnClickListener(this);
        Single<Boolean> single = SharedPrefStorage.readMessage(DataCenter.KEY_LOCAL_PUSH, true);
        single.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onSuccess(Boolean aBoolean) {
                        aSwitchPush.setChecked(aBoolean);
                        aSwitchPush.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                if (isChecked) {
                                    PushChannel.getHandler().resumePush();
                                    //JPushInterface.resumePush(buttonView.getContext().getApplicationContext());
                                } else {
                                    PushChannel.getHandler().stopPush();
                                    //JPushInterface.stopPush(buttonView.getContext().getApplicationContext());
                                }

                                SharedPrefStorage.writeMessage(DataCenter.KEY_LOCAL_PUSH, isChecked);
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                });
        tvVersionStatus.setText("V" + BuildConfig.VERSION_NAME);
        versionImageView.setVisibility(View.GONE);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MessageCenter.INSTANCE.getUpgradeInfoLiveData().removeObservers(this);
    }


    private void changeStatus(UpgradeInfoMsg upgradeInfoMsg) {
        if (upgradeInfoMsg.getChecking()) {
            tvVersionStatus.setText("正在检查更新");
            versionImageView.setImageResource(R.drawable.clean_filer);
            versionImageView.setVisibility(View.VISIBLE);
            versionImageView.animate().rotation(108000).setDuration(150000).start();
            versionChecking = true;
        } else if (upgradeInfoMsg.getHasNewVersion()) {
            final UpgradeInfo upgradeInfo = upgradeInfoMsg.getUpgradeInfo();
            if (upgradeInfo != null && !TextUtils.isEmpty(upgradeInfo.versionName)) {
                tvVersionStatus.setText("V" + upgradeInfo.versionName);
            } else {
                tvVersionStatus.setText("发现新版本");
            }
            versionImageView.animate().cancel();
            versionImageView.setVisibility(View.VISIBLE);
            versionImageView.setMinimumWidth(AndroidUtilities.dp(8));
            versionImageView.setMinimumHeight(AndroidUtilities.dp(8));
            versionImageView.setImageResource(R.drawable.red_point);

        } else {
            tvVersionStatus.setText("V" + BuildConfig.VERSION_NAME);
            versionImageView.animate().cancel();
            versionImageView.setVisibility(View.GONE);
            ToastUtils.showText("已经是最新版本");

        }
    }

    private void checkVersion() {
//        UpgradeConfigure.checkUpgrade(true,false);
//        MessageCenter.INSTANCE.getUpgradeInfoLiveData().observeForever(
//                new Observer<UpgradeInfoMsg>() {
//                    @Override
//                    public void onChanged(@Nullable UpgradeInfoMsg upgradeInfoMsg) {
//                        if (upgradeInfoMsg != null && hasClick){
//                            //手动更新
//                            changeStatus(upgradeInfoMsg);
//                        }
//                    }
//                });
//        if (upgradeModelObserver == null) {
//            //应用更新
//            upgradeModelObserver = new Observer<UpgradeModel>() {
//                @Override
//                public void onChanged(@Nullable UpgradeModel upgradeModel) {
//                    //有更新
//                    try {
//                        if (upgradeModel != null) {
//                            if (upgradeModel.getShowMarketDialog()) {
//                                //支持本地打开
//                                //点击了更新
//                                StatTools.sendShow(getActivity(), StatisticsId.upgrade_click, upgradeModel.getJumpMarket());
//                                UpdateTools.INSTANCE.startMarket(getActivity(), upgradeModel);
//                            }
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        MainActUtils.checkAndShow(true);
//                    }
//                }
//            };
//            MessageCenter.INSTANCE.getMainUpgradeLiveData().observeForever(
//                    upgradeModelObserver);
//        }
    }

    private void checkUpdate() {
        tvVersionStatus.setText("正在检查更新");
        versionImageView.setImageResource(R.drawable.clean_filer);
        versionImageView.setVisibility(View.VISIBLE);
        versionImageView.animate().rotation(108000).setDuration(150000).start();
        versionChecking = true;
        Single.timer(2000, TimeUnit.MILLISECONDS).flatMap((Function<Long, SingleSource<Optional<UpgradeModel>>>) aLong ->
                Api.get().checkVersionInfo()).subscribe(new ApiOptionalResultObserver<UpgradeModel>() {
            @Override
            protected void onApiResult(@Nullable UpgradeModel value) {
                if (value != null && BuildConfig.VERSION_CODE < value.getVersionCode()) {
                    versionImageView.animate().cancel();
                    versionImageView.setVisibility(View.GONE);
                    StatTools.sendShow(getActivity(), StatisticsId.upgrade_click, value.getJumpMarket());
                    UpdateTools.INSTANCE.startMarket(getActivity(), value);
                    tvVersionStatus.setText("V" + BuildConfig.VERSION_NAME);
                    Toast.makeText(getActivity(), "发现最新版本", Toast.LENGTH_SHORT).show();
                } else {
                    tvVersionStatus.setText("V" + BuildConfig.VERSION_NAME);
                    versionImageView.animate().cancel();
                    versionImageView.setVisibility(View.GONE);
                    ToastUtils.showText("已经是最新版本");
                }
            }

            @Override
            protected void onApiError(@Nullable BaseResult result) {
                toastErrorMsg(result);
                tvVersionStatus.setText("V" + BuildConfig.VERSION_NAME);
            }
        });
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        switch (id) {
            case R.id.rl_pwd:
                UserMode mode = center.getUserMode();
                if (mode != null) {
                    if (mode.isSetPwd) {
                        startActivity(PwdActivity.asIntent(getContext(), PreChangePwdFragment.TAG));
                    } else {
                        startActivity(PwdActivity.asIntent(getContext(), PreSetupPwdFragment.TAG));
                    }
                }

                break;
            case R.id.rl_listener:
                //todo
//                String url = "http://wwww.baidu.com";
//                CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
//                CustomTabsIntent customTabsIntent = builder.build();
//                customTabsIntent.launchUrl(getActivity(), Uri.parse(url));
//                WebViewActivity.startWebview(getContext(), "http://www.baidu.com");
//                startActivity(MineActivity.asIntent(getContext(), ListenerFragment.TAG));
                if (TextUtils.equals(ChannelManager.getChannel(), "huawei")) {
                    RouterUtils.startWeb(v.getContext(), ConfigsKt.getH5_TERMS_OF_SERVICE() + "?platform=jtzx");
                } else {
                    RouterUtils.startWeb(v.getContext(), ConfigsKt.getH5_TERMS_OF_SERVICE());
                }
                break;
            case R.id.rl_privacy_policy:
                RouterUtils.start(v.getContext(), RPaths.SETTINGS_PRIVACY);
                //RouterUtils.startWeb(v.getContext(), ConfigsKt.getH5_PRIVACY_POLICY());
                break;

            case R.id.rl_feedback:
                RouterUtils.start(v.getContext(), RPaths.feedback);
//                startActivity(MineActivity.asIntent(getContext(),RPaths.feedback));
                //RouterUtils.startWeb(v.getContext(), ConfigsKt.getH5_PRIVACY_POLICY());
                break;
            case R.id.rl_version:
                hasClick = true;
                checkUpdate();
//                checkVersion();
                break;

        }
    }


    @Override
    public String getFragmentTitle() {
        return "设置";
    }

    @Override
    public Activity activity() {
        return getActivity();
    }
}
